<template>
  <div class="app-container">
    <!-- 第一行：左1+左2 vs 右1 -->
    <el-row :gutter="10" class="row-block">
      <!-- 左1+左2组合 -->
      <el-col :span="14" class="left-combo">
        <!-- 左1 (20%) -->
        <div class="left-top section-card" style="height:154px;border-radius: 8px;">
          <div style="display: flex;width: 100%;height: 100%;justify-content: space-between">
            <div
              style="width: 33%;background-color: white;height: 100%;border-radius: 5px;display: flex;padding-left: 40px;">
              <img src="@/assets/images/market.svg" style="width: 83px;height: 83px;margin-top: 34px;" alt="">
              <div style="margin-top: 34px;margin-left: 23px;">
                <div style="color: #848484;font-size: 14px;">
                  今日销售额
                </div>
                <div style="font-size: 24px;color: black;margin: 8px 0;">
                  {{ formTopObj.todayAmount }}
                </div>
                <div style="color: #848484;font-size: 14px;">
                  昨日全天 {{ formTopObj.yesterdayAmount }}
                </div>
              </div>
            </div>
            <div
              style="width: 33%;background-color: white;height: 100%;border-radius: 5px;display: flex;padding-left: 40px;"
              @click="dingds">
              <img src="@/assets/images/orderform.svg" style="width: 83px;height: 83px;margin-top: 34px;" alt="">
              <div style="margin-top: 34px;margin-left: 23px;">
                <div style="color: #848484;font-size: 14px;">
                  今日订单量
                </div>
                <div style="font-size: 24px;color: black;margin: 8px 0;">
                  {{ formTopObj.todayOrderNum }}
                </div>
                <div style="color: #848484;font-size: 14px;">
                  昨日全天 {{ formTopObj.yesterdayOrderNum }}
                </div>
              </div>
            </div>
            <!-- template -->
            <div class="card-wrap">
              <!-- 原来你写的卡片 -->
              <div class="card-inner">
                <img src="@/assets/images/earlywarning.svg" class="icon" alt="">
                <div class="info">
                  <div class="label">智能预警</div>
                  <div class="count">{{ formTopObj.allAlarm }}</div>
                  <div class="sub">
                    <span @click="shicai">食材预警 {{ formTopObj.ingredientsAlarm }}</span>
                    <span class="ml12" style="padding-left: 15px;" @mouseenter="openPopover"
                      @mouseleave="startCloseTimer">突发波动 {{ formTopObj.fluctuateAlarm }}</span>
                  </div>
                </div>
              </div>

              <!-- 悬浮弹框 -->
              <div v-show="showList" class="pop-list" style="padding:20px;" @mouseenter="cancelClose"
                @mouseleave="closePopover">
                <div class="custom-dialog-title">
                  <div style="display: flex;padding-bottom: 15px;">
                    <div
                      style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;">
                    </div>
                    <span class="title-text"
                      style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;text-align: center;letter-spacing: normal;color: #3D3D3D;">突发波动</span>
                  </div>
                </div>

                <div style="display: flex;justify-content: space-between;font-size: 14px;margin-bottom: 8px;">
                  <div style="width: 50%;">事件</div>
                  <div style="width: 30%;">时间</div>
                  <div style="width: 20%;text-align: right;">操作</div>
                </div>
                <div v-for="(item, idx) in alarmList" :key="idx"
                  style="display: flex;justify-content: space-between;font-size: 14px;" class="pop-item">
                  <div style="width: 50%;color: black;margin-top: 5px;">
                    <!-- {{ item.noticeContent }} -->
                    <el-tooltip class="item" effect="dark" :content="item.noticeContent" placement="top-start">
                      <div style="height: 30px;width: 90%;overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;">
                        {{ item.noticeContent }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div style="width: 30%;color: #848484;margin-top: 8px;">
                    {{ item.createTime }}
                  </div>
                  <div style="width: 20%;text-align: right;">
                    <el-button type="text" size="small" @click="picked(item)" v-if="item.status == 0"
                      style="color: #4C6EE2;">处理</el-button>
                    <el-button type="text" size="small" @click="picked(item)" v-else
                      style="color: green;">已处理</el-button>
                  </div>
                </div>
                <div v-if="!alarmList.length" class="empty">暂无预警</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 左2 (40%) -->
        <div class="left-middle" style="height:391px;border-radius: 8px;">
          <el-card class="section-card">
            <div
              style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
              <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
                订餐人数统计</div>
              <div style="color: #848484;font-size: 14px;margin-top: 4px;">
                开始时间：
                <el-date-picker v-model="beginTimeReservation" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd" style="
                width: 117px;
                height: 26px;
              " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''"
                  @change="peopleCounting"></el-date-picker>
                结束时间：
                <el-date-picker v-model="overTimeReservation" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd" style="
    width: 117px;
    height: 26px;
  " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''" @change="peopleCounting"></el-date-picker>
              </div>
            </div>
            <div id="reservationbd" style="width: 100%;height: 300px;"></div>
            <!-- <div
              style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
              <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;margin-top: -1px;">
                实时看板</div>
              <div style="color: #848484;font-size: 14px;">
                实时看板数据为下周预订餐量
              </div>
            </div>
            <div
              style="background-color: rgb(245, 247, 254);height: 44px;width: 100%;border-radius: 10px;line-height: 44px;padding: 0 20px;display: flex;justify-content: space-between">
              <div style="display: flex;">
                <span style="font-size: 14px;">
                  总备餐量：
                </span>
                <span style="font-size: 20px;color: #4C6EE2;padding-top: 1px;">
                  {{ boardListNum }}
                </span>
              </div>
              <div style="display: flex;">
                <span style="font-size: 14px;">
                  {{ formatDate(getNextWeekDates().nextMonday) }}至
                  {{ formatDate(getNextWeekDates().nextSunday) }}
                </span>
              </div>
            </div>
            <div id="boardl" style="width: 100%;height: 270px;"></div> -->
          </el-card>
        </div>
      </el-col>

      <!-- 右1 (55%) -->
      <el-col :span="10" class="right-top" style="height:540px">
        <el-card class="section-card">
          <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;margin-top: -1px;">
              审批待办</div>
            <div style="color: #848484;font-size: 14px;">
              {{ timeApp || getFormattedDate() }}
            </div>
          </div>

          <!-- 使用日历组件替换原有日历 -->
          <week-calendar ref="weekCalendar" :initial-date="initialSelectedDate" @date-selected="handleDateSelected"
            @week-changed="handleWeekChanged" />

          <div style="">
            <div v-for="(item, index) in urgencyList" :key="index"
              style="padding:12px;display: flex;border-bottom: 1px solid rgb(237, 240, 252);">
              <div style="width: 85%;">
                <div style="font-size: 14px;font-weight: 600;">
                  {{ item.type == 1 ? "套餐审批" : "员工订餐审批" }}
                </div>
                <div class="ellipsis" style="font-size: 12px;color: #848484;margin-top: 10px;">
                  {{ item.content }}
                </div>
              </div>

              <div style="width: 15%;text-align: right;">
                <div style="height: 19px;font-size: 12px;color: #848484;">
                  {{ item.approvalTime }}
                </div>
                <div>
                  <el-button type="text" size="small" @click="handleApprove(item)"
                    v-if="item.status == '1'">同意</el-button>
                  <el-button type="text" size="small" @click="handleReject(item)"
                    v-if="item.status == '1'">拒绝</el-button>
                </div>
              </div>
            </div>

            <div style="color: #4C6EE2;text-align: center;font-weight: 600;margin-top: 10px;"
              v-if="urgencyList.length >= 4" @click="tcapp">
              查看更多
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：左3 vs 右2 -->
    <el-row :gutter="10" class="row-blocks" style="height: 443px;">
      <!-- 左3 (40%) -->
      <el-col :span="14" class="left-bottom" style="height:100%">
        <el-card class="section-card">
          <!-- <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              历史追溯</div>
            <div style="color: #848484;font-size: 14px;margin-top: 4px;">
              选择周：
              <el-date-picker v-model="beginTimeCuisine" type="week" :clearable="false" format="yyyy 第 WW 周"
                :picker-options="{ 'firstDayOfWeek': 1 }" placeholder="选择周" @change="history">
              </el-date-picker>
            </div>

          </div>
          <div id="history" style="width: 100%;height: 350px;"></div> -->
            <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;margin-top: -1px;">
              实时看板</div>
            <div style="color: #848484;font-size: 14px;">
              实时看板数据为下周预订餐量
            </div>
          </div>
          <div
            style="background-color: rgb(245, 247, 254);height: 44px;width: 100%;border-radius: 10px;line-height: 44px;padding: 0 20px;display: flex;justify-content: space-between">
            <div style="display: flex;flex-wrap: wrap;">
              <div>
                <span style="font-size: 14px;">
                  总备餐量：
                </span>
                <span style="font-size: 20px;color: #4C6EE2;padding-top: 1px;">
                  {{ boardListNum }}
                </span>
              </div>
                <div v-for="(value, index) in boardListNumList" :key="index" style="margin-left: 15px;">
                <span style="font-size: 14px;">
                  {{ value.name }}:
                </span>
                <span style="font-size: 14px;color: #4C6EE2;padding-top: 1px;">
                  {{ value.count }}
                </span>
            </div>
            </div>
            <div style="display: flex;">
              <span style="font-size: 14px;">
                {{ formatDate(getNextWeekDates().nextMonday) }}至
                {{ formatDate(getNextWeekDates().nextSunday) }}
              </span>
            </div>
          </div>
          <div id="boardl" style="width: 100%;height: 320px;"></div>
        </el-card>
      </el-col>

      <!-- 右2 (45%) -->
      <el-col :span="10" class="right-bottom" style="height:100%">
        <el-card class="section-card">
          <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              食材映射</div>
            <div style="color: #848484;font-size: 14px;margin-top: 4px;">
              <!-- 开始时间：
              <el-date-picker v-model="beginTime" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd" style="
                width: 117px;
                height: 26px;
              " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''"
                @change="history"></el-date-picker>
              <span style="margin-left: 10px;">
                结束时间：
                <el-date-picker v-model="overTime" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd" style="
                    width: 117px;
                    height: 26px;
                    
                  " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''"
                  @change="history"></el-date-picker>
              </span> -->

              <el-button
                style="background-color: #4C6EE2;color: white;height: 26px;width: 48px;text-align: center;padding: 0;border-radius: 5px;margin-left: 10px;"
                size="mini" @click="ingredientExp">导出</el-button>
            </div>
          </div>
          <div style="overflow: auto;height: 340px;">
            <el-table :data="tableDataCuisine" style="width: 100%;" :row-class-name="tableRowClassName">
              <el-table-column prop="food_name" label="菜品名称" align="left">
              </el-table-column>
              <el-table-column prop="ingredientsName" label="食材名称" align="left">
              </el-table-column>
              <el-table-column prop="num" label="单份用量" align="left">
              </el-table-column>
              <el-table-column prop="rate" label="损耗率" width="70" align="left">
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 第三行：左3 vs 右2 -->
    <el-row :gutter="10" class="row-blocks" style="height: 443px;">
      <!-- 左3 (40%) -->
      <el-col :span="14" class="left-bottom" style="height:100%">
        <el-card class="section-card">
              <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              历史追溯</div>
            <div style="color: #848484;font-size: 14px;margin-top: 4px;">
              选择周：
              <el-date-picker v-model="beginTimeCuisine" type="week" :clearable="false" format="yyyy 第 WW 周"
                :picker-options="{ 'firstDayOfWeek': 1 }" placeholder="选择周" @change="history">
              </el-date-picker>
            </div>

          </div>
          <div id="history" style="width: 100%;height: 350px;"></div>
          <!-- <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;margin-top: -1px;">
              实时看板</div>
            <div style="color: #848484;font-size: 14px;">
              实时看板数据为下周预订餐量
            </div>
          </div>
          <div
            style="background-color: rgb(245, 247, 254);height: 44px;width: 100%;border-radius: 10px;line-height: 44px;padding: 0 20px;display: flex;justify-content: space-between">
            <div style="display: flex;flex-wrap: wrap;">
              <div>
                <span style="font-size: 14px;">
                  总备餐量：
                </span>
                <span style="font-size: 20px;color: #4C6EE2;padding-top: 1px;">
                  {{ boardListNum }}
                </span>
              </div>
              <div v-for="(value, index) in boardListNumList" :key="index" style="margin-left: 30px;">
                <span style="font-size: 14px;">
                  {{ value.name }}:
                </span>
                <span style="font-size: 14px;color: #4C6EE2;padding-top: 1px;">
                  {{ value.count }}
                </span>
              </div>
            </div>
            <div style="display: flex;">
              <span style="font-size: 14px;">
                {{ formatDate(getNextWeekDates().nextMonday) }}至
                {{ formatDate(getNextWeekDates().nextSunday) }}
              </span>
            </div>
          </div>
          <div id="boardl" style="width: 100%;height: 320px;"></div> -->

        </el-card>
      </el-col>

      <!-- 右2 (45%) -->
      <el-col :span="10" class="right-bottom" style="height:100%">
        <el-card class="section-card">
          <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              淘汰建议清单
              <!-- <i class="el-icon-question"></i> -->
              <el-tooltip class="item" effect="dark" placement="top-start">
                <!-- 触发器 -->
                <i class="el-icon-question"></i>

                <!-- 自定义内容 -->
                <template #content>
                  <div class="custom-tooltip">
                    <div class="formula-line">
                      (周实际预订量*50% + 周实际点击量 *30% - 周实际取消量 *20%） * 100
                    </div>
                    <div class="calc-line">
                      <!-- 标准化值计算：预订量/2500 | 点击量/22500 | 取消量/总预订量 -->
                    </div>
                    <div class="data-line">
                      <!-- 数据基准：周均值预订2500 | 点击22500 -->
                    </div>
                  </div>
                </template>
              </el-tooltip>
            </div>
            <div style="color: #848484;font-size: 12px;margin-top: 4px;">
              菜品热度：点击量/预订量/取消量
            </div>
          </div>
          <div style="height: 350px; overflow: auto;">
            <el-table :data="nationList.slice(0, 20)" style="width: 100%">
              <el-table-column prop="date" label="排行" width="180" align="left">
                <template #default="{ $index }">
                  <img src="@/assets/images/one.png" v-if="$index == 0" alt="" style="width: 24px;height: 27px;">
                  <img src="@/assets/images/two.png" v-else-if="$index == 1" alt="" style="width: 24px;height: 27px;">
                  <img src="@/assets/images/three.png" v-else-if="$index == 2" alt="" style="width: 24px;height: 27px;">
                  <div v-else style="padding-left: 10px;">
                    {{ $index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="foodName" label="菜品名称" align="left">
              </el-table-column>
              <el-table-column prop="score" label="菜品热度" align="left">
                <template slot="header">
                  <div class="header-with-formula">
                    <span>菜品热度</span>
                    <el-tooltip effect="dark" placement="top">
                      <div slot="content" class="formula-tooltip">
                        <h4>热度计算公式</h4>
                        <div class="formula-block">
                          <div>
                            (周实际预订量*50% + 周实际点击量 *30% - 周实际取消量 *20%） * 100
                            <!-- (周实际预订量 /（ 现有员工数量*一周7天） * 3次)*50% + -->
                          </div>
                          <div>
                            <!-- (周实际点击量 / （ 现有员工数量*一周7天 * 3次）)*30% - -->
                          </div>
                          <div>
                            <!-- (周实际取消量 / 总预订量)*20%] * 100 -->
                          </div>
                        </div>
                        <div class="divider"></div>

                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="address" width="80" label="是否停用" align="left">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-color="#4C6EE2" active-value="1" inactive-value="0"
                    @change="(val) => changeSwitch(val, scope.row)">
                  </el-switch>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第四行：左3 vs 右2 -->
    <el-row :gutter="10" class="row-blocks" style="height: 443px;">
      <!-- 左3 (40%) -->
      <el-col :span="14" class="left-bottom" style="height:100%">
        <el-card class="section-card">
          <div
            style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;display: flex;justify-content: space-between">
            <div><img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              深度分析</div>
            <!-- <div style="color: #848484;font-size: 14px;margin-top: 4px;">
              开始时间：
              <el-date-picker v-model="beginTimeAnalyse" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd" style="
                width: 117px;
                height: 26px;
              " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''"
                @change="deepAnal"></el-date-picker>
              结束时间：
              <el-date-picker v-model="overTimeAnalyse" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                value-format="yyyy-MM-dd" style="
    width: 117px;
    height: 26px;
  " :popper-class="'small-date-picker'" :prefix-icon="''" :clear-icon="''" @change="deepAnal"></el-date-picker>
            </div> -->
                  <el-date-picker v-model="beginTimeAnalyse" type="week" :clearable="false" format="yyyy 第 WW 周"
                :picker-options="{ 'firstDayOfWeek': 1 }" placeholder="选择周" @change="deepAnal">
              </el-date-picker>
          </div>
          <div id="deepAnalysis" style="width: 100%;height: 350px;"></div>
        </el-card>
      </el-col>

      <!-- 右2 (45%) -->
      <el-col :span="10" class="right-bottom" style="height:100%">
        <div class="section-card"
          style="height: 440px;background-color: white;margin-top: 5px;border-radius: 8px;box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);">

          <div :class="changeMenu ? 'activeche' : 'activeches'"
            style="font-size: 20px;font-weight: 600;padding: 12px 0;padding-bottom: 30px; margin-top: -4px;display: flex;justify-content: space-around">
            <div @click="onSwitchingMent(true)" style="width: 50%;text-align: center;"><img
                src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              受欢迎菜统计</div>

            <div @click="onSwitchingMent(false)" style="width: 50%;text-align: center;"><img
                src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 3px;">
              经典菜统计</div>
          </div>

          <!-- 
          <div>
            <div style="color: #848484;font-size: 14px;margin-top: 4px;text-align: right;margin-right: 15px;margin-bottom: 5px;">
              <el-button
                style="background-color: #4C6EE2;color: white;height: 26px;width: 48px;text-align: center;padding: 0;border-radius: 5px;margin-left: 10px;"
                size="mini" @click="cookingExp">导出</el-button>
            </div>
          </div> -->
          <div style="padding: 10px 15px;height: 340px;overflow: auto;">
            <el-table :data="changeMenu ? classicDishList : classiwelcomeList" style="width: 100%">
              <el-table-column prop="date" label="排名" align="left">
                <template #default="{ $index }">
                  <img src="@/assets/images/one.png" v-if="$index == 0" alt="" style="width: 24px;height: 27px;">
                  <img src="@/assets/images/two.png" v-else-if="$index == 1" alt="" style="width: 24px;height: 27px;">
                  <img src="@/assets/images/three.png" v-else-if="$index == 2" alt="" style="width: 24px;height: 27px;">
                  <div v-else style="padding-left: 10px;">
                    {{ $index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="foodName" label="菜品名称" align="left">
              </el-table-column>
              <el-table-column prop="score" label="菜品热度" align="left">
                <template slot="header">
                  <div class="header-with-formula">
                    <span>菜品热度</span>
                    <el-tooltip effect="dark" placement="top">
                      <div slot="content" class="formula-tooltip">
                        <h4>热度计算公式</h4>
                        <div class="formula-block">
                          <div>
                            (周实际预订量*50% + 周实际点击量 *30% - 周实际取消量 *20%） * 100
                            <!-- (周实际预订量 /（ 现有员工数量*一周7天） * 3次)*50% + -->
                          </div>
                          <div>
                            <!-- (周实际点击量 / （ 现有员工数量*一周7天 * 3次）)*30% - -->
                          </div>
                          <div>
                            <!-- (周实际取消量 / 总预订量)*20%] * 100 -->
                          </div>
                        </div>
                        <div class="divider"></div>

                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="confirmSaleNum" label="累计预定量" width="180" align="left">
              </el-table-column>
              <el-table-column prop="taste" label="口味" width="80" align="left">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getboard, historyent, ingredstatistics, inuserrdere, ingrstatistrapList, foodclassic, statisticsdic, sttopmber, sttofluctuater, sttoflhandleer } from "@/api/indexs.js"
import { getList, submitApproval, changerovall } from '@/api/urgency'
import { dishUpdate } from '@/api/cuisine'


import WeekCalendar from './WeekCalendar.vue';

export default {
  name: 'Dashboard',
  components: {
    WeekCalendar
  },
  data() {
    const today = new Date();

    return {
      showList: false,
      closeTimer: null,
      changeMenu: true,
      classicDishList: [],
      showList: false,
      alarmList: [
      ],
      tableDataCuisine: [],
      localIp: "",
      ipAddress: { ip: "", location: "", type: "" },
      boardListNum: 0,
      overTime: "",
      beginTime: "",
      overTimeCuisine: "",
      beginTimeCuisine: "",
      beginTimeAnalyse: "",
      overTimeAnalyse: "",
      beginTimeReservation: "",
      overTimeReservation: "",
      urgencyList: [],
      boardListNumList: [],
      nationList: [],
      classiwelcomeList: [],
      formTopObj: {

      },
      timeApp: "",
      initialSelectedDate: this.getFormattedDate(), // 日历组件初始选中日期
    }
  },
  mounted() {
    const { monday, sunday } = this.getCurrentWeekDates();
    this.beginTime = monday;
    this.overTime = sunday;
    this.beginTimeCuisine = monday;
    this.overTimeCuisine = sunday;
    this.beginTimeAnalyse = monday;
    this.overTimeAnalyse = sunday;
    this.beginTimeReservation = this.formatDate(this.getNextWeekDates().nextMonday);
    this.overTimeReservation = this.formatDate(this.getNextWeekDates().nextSunday);

    this.topOnclick();
    this.getIpAddress();
    this.board();
    this.history();
    this.approve();
    this.cuisineList()
    this.deepAnal()
    this.peopleCounting()
    this.Ingredient()
    // this.welcome()
    this.eliminationList()
    this.tofaList()
    // foodclassic

  },
  methods: {
    openPopover() {
      this.cancelClose() // 先清除可能的关闭计时器
      this.showList = true
    },

    startCloseTimer() {
      // 设置关闭延迟（500ms比300ms更友好）
      this.closeTimer = setTimeout(() => {
        this.showList = false
      }, 500)
    },

    cancelClose() {
      // 鼠标进入弹出框时取消关闭
      clearTimeout(this.closeTimer)
    },

    closePopover() {
      // 鼠标离开弹出框时立即关闭
      this.showList = false
    },

    beforeDestroy() {
      clearTimeout(this.closeTimer)
    },
    dingds() {
      this.$router.push("/indent/indent")
    },
    async picked(row) {
      const res = await sttoflhandleer({
        noticeId: row.noticeId,
        status: row.status == 0 ? 1 : 0,
        comboId: row.comboId,
        type: row.type
      })
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      this.tofaList()
    },
    async tofaList() {
      const res = await sttofluctuater()
      this.alarmList = res.data
    },
    async topOnclick() {
      const res = await sttopmber();
      console.log(res.data)
      this.formTopObj = res.data;
    },
    async changeSwitch(val, id) {
      const res = await dishUpdate({
        foodId: id.foodId,
        foodName: id.foodName,
        status: val
      })
    },
    async eliminationList() {
      const res = await statisticsdic()
      this.nationList = res.data
      this.classicDishList = [...res.data].sort().reverse();
      this.classiwelcomeList = [...this.classicDishList].sort((a, b) => b.confirmSaleNum - a.confirmSaleNum);
      // console.log
    },
    shicai() {
      this.$router.push("/ingredient/ingredient")
    },
    cookingExp() {
      if (this.changeMenu) {

      } else {
        this.downloads(`food/statistics/classicsList/export`, {
        }, `经典菜导出${new Date().toISOString().slice(0, 10)}.xlsx`);
      }
    },
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 !== 0 ? 'even-row' : 'odd-row';
    },
    // welcome() {
    //   this.classicDishList = []
    // },
    async classicDish() {
      const res = await foodclassic()
      this.classicDishList = res.data
    },
    ingredientExp() {
      this.downloads(`food/statistics/rapList/export`, {
      },
        `食材映射导出${new Date().toISOString().slice(0, 10)}.xlsx`);
    },
    async Ingredient() {
      const res = await ingrstatistrapList()
      console.log(res.rows)
      this.tableDataCuisine = res.rows
    },
    onSwitchingMent(val) {
      this.changeMenu = val
      //  if (val) {
      //   this.eliminationList()
      //  } else {
      //   this.classicDish()
      //  }
    },
    async peopleCounting() {
      const res = await inuserrdere({
        beginTime: this.beginTimeReservation,
        endTime: this.overTimeReservation
      });

      const chartDom = document.getElementById('reservationbd');
      const myChart = echarts.init(chartDom);

      // Generate all dates in the selected range
      const startDate = new Date(this.beginTimeReservation);
      const endDate = new Date(this.overTimeReservation);
      const allDates = [];

      for (let date = new Date(startDate); date <= endDate; date.setDate(date.getDate() + 1)) {
        const dateStr = date.toISOString().split('T')[0];
        allDates.push(dateStr);
      }

      // Create a map of the returned data for easy lookup
      const dataMap = new Map();
      res.data.forEach(item => {
        dataMap.set(item.date, item.orderUserNum);
      });

      // Prepare the complete data with all dates
      const completeData = allDates.map(date => {
        return {
          date: date,
          orderUserNum: dataMap.get(date) || 0
        };
      });

      const option = {
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            lineStyle: {
              color: '#4C6EE2'
            }
          },
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          extraCssText: 'box-shadow: none;',
          formatter: function (params) {
            return `
          <div style="padding: 10px 18px; background: #fff; border-radius: 9px; box-shadow:  0px 0px 10px 0px rgba(48, 78, 179, 0.3);">
            <div style="font-weight: bold; color: #333; margin-bottom: 5px">
              <span style="
                display: inline-block;
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background: #4C6EE2;
                position: relative;
              ">
                <span style="
                  position: absolute;
                  top: 2px;
                  left: 2px;
                  width: 6px;
                  height: 6px;
                  border-radius: 50%;
                  background: #fff;
                "></span>
              </span>
              ${params[0].name}
            </div>
            <div style="display: flex; align-items: center;margin-left:15px;color:black;">
              <span>${params[0].seriesName}</span>
              <span style=" margin-left: 4px;">${params[0].value} 人</span>
            </div>
          </div>
        `;
          }
        },
        grid: {
          left: '2%',
          right: '5%',
          bottom: '10%',
          top: "15%",
          containLabel: true
        },
        dataZoom: [{
          type: 'slider',
          xAxisIndex: 0,
          height: 5,
          bottom: 10,
          backgroundColor: '#e0e0e0',
          fillerColor: '#4C6EE2',
          borderColor: 'transparent',
          handleIcon: 'none',
          handleSize: '0%',
          moveHandleSize: 0,
          brushSelect: false,
          showDetail: false,
          borderRadius: 10,
          minValueSpan: 10,
          startValue: 'dataMin',
          endValue: 'dataMax',
          zoomLock: false,
          filterMode: 'filter'
        }],
        xAxis: [{
          type: 'category',
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          },
          axisLabel: {
            padding: [0, 0, 0, 0],
            color: '#323232',
            interval: 0, // 显示所有标签
            // 关键配置：强制换行
            formatter: function (value) {
              // 每4个字符插入换行符
              return value.match(/.{1,6}/g).join('\n');
            },
            lineHeight: 16, // 行高
            fontSize: 10    // 缩小字体
          },
          data: completeData.map(el => el.date.slice(5))
        }],
        yAxis: [{
          type: 'value',
          name: '单位：人',
          splitNumber: 5,
          nameTextStyle: {
            padding: [0, 0, 0, "-15"],
            color: '#3D3D3D'
          },
          min: 0,
          max: function (value) {
            return (value.max < 5 ? 5 : null);
          },
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              type: 'dashed',
              color: '#3D3D3D'
            }
          },
          axisLabel: {
            textStyle: {
              fontSize: 14,
              color: '#3D3D3D'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          },
        }],
        series: [{
          name: '预定人数：',
          type: 'bar',
          barWidth: 24,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#4C6EE2' },
              { offset: 1, color: '#4C6EE2AA' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#3A56C4' },
                { offset: 1, color: '#3A56C4AA' }
              ])
            }
          },
          data: completeData.map(el => el.orderUserNum)
        }]
      };

      myChart.setOption(option);
    },
    async deepAnal(e) {

        const Ts = this.getWeekRange(e);
      const res = await ingredstatistics({ beginTime: e ? Ts.monday : this.beginTimeAnalyse, endTime: e ? Ts.sunday : this.overTimeAnalyse });
      // const res = await ingredstatistics(
      //   {
      //     beginTime: this.beginTimeAnalyse,
      //     endTime: this.overTimeAnalyse
      //   }
      // )
      console.log(res.data.data)
      const chartDom = document.getElementById('deepAnalysis');
      const myChart = echarts.init(chartDom);

      const T = res.data.map(el =>
        el.foodName
      ).filter(el => el)
      console.log(T)

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // axisPointer: {
          //   lineStyle: {
          //     color: '#4C6EE2'
          //   }
          // },
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          extraCssText: 'box-shadow: none;',
          formatter: function (params) {
            // 获取三种数据的值（兼容可能的数据缺失情况）
            const clickVal = params.find(item => item.seriesName === '点击量')?.value || 0;
            const bookVal = params.find(item => item.seriesName === '预订量')?.value || 0;
            const cancelVal = params.find(item => item.seriesName === '取消量')?.value || 0;

            return `
    <div style="padding: 10px 18px; width:230px; background: #fff; border-radius: 9px; box-shadow: 0px 0px 10px 0px rgba(48, 78, 179, 0.3);">
      <div style="font-weight: bold; color: #333; margin-bottom: 8px; display: flex; align-items: center;">
       
        ${params[0].axisValue} <!-- 使用 axisValue 替代 name 更准确 -->
      </div>
      
     <div style="display: flex; justify-content: space-between;" >
          <!-- 点击量 -->
          <div style="margin: 6px 0; ">
             <span style="
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: #4C6EE2;
          position: relative;
        ">
          <span style="
            position: absolute;
            top: 2px;
            left: 2px;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #fff;
          "></span>
        </span>
            <span style="color: #666;">点击量</span>
            <span style=" font-weight: bold;">${clickVal} </span>
          </div>
          
          <!-- 预订量 -->
          <div style="margin: 6px 0;">
              <span style="
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: #5EB931;
          position: relative;
        ">
          <span style="
            position: absolute;
            top: 2px;
            left: 2px;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #fff;
          "></span>
        </span>
            <span style="color: #666;">预订量</span>
            <span style=" font-weight: bold;">${bookVal} </span>
          </div>
      </div>
      
      <!-- 取消量 -->
      <div style=" margin: 6px 0;">
         <span style="
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: #FF9626;
          position: relative;
        ">
          <span style="
            position: absolute;
            top: 2px;
            left: 2px;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #fff;
          "></span>
        </span>
        <span style="color: #666;">取消量</span>
        <span style=" font-weight: bold;">${cancelVal}</span>
      </div>
    </div>
  `;
          }
        },
        grid: {
          left: '2%',
          right: '5%',
          bottom: '10%',
          top: "15%",
          containLabel: true
        },
        dataZoom: [{
          type: 'slider',
          xAxisIndex: 0,
          height: 5,
          bottom: 10,
          backgroundColor: '#e0e0e0',
          fillerColor: '#4C6EE2',
          borderColor: 'transparent',
          handleIcon: 'none',
          handleSize: '0%',
          moveHandleSize: 0,
          brushSelect: false,
          showDetail: false,
          borderRadius: 10,
          // 关键配置开始
          minValueSpan: 8,  // 最小显示10个数据项
          startValue: 'dataMin',  // 从第一个数据开始
          endValue: 'dataMax',   // 到最后一个数据结束
          zoomLock: false,      // 允许缩放
          filterMode: 'filter'  // 过滤模式
          // 关键配置结束
        }],
        legend: {
          data: ['点击量', '预订量', '取消量'],
          right: '2%',
        },
        xAxis: {
          type: 'category',
          data: T,  // 添加第四个类别
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          },
          axisLabel: {
            padding: [0, 0, 0, 0],
            color: '#323232',
            interval: 0, // 显示所有标签
            // 关键配置：强制换行
            formatter: function (value) {
              // 每4个字符插入换行符
              return value.match(/.{1,6}/g).join('\n');
            },
            lineHeight: 16, // 行高
            fontSize: 10    // 缩小字体
          },
        },
        yAxis: {
          type: 'value',
          name: '单位：次',
          min: 0,
          max: function (value) {
            return (value.max < 5 ? 5 : null); // 向下取整
          },
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          },
          nameTextStyle: {
            padding: [0, 0, 0, "-15"],
            color: '#3D3D3D'
          },
        },
        series: [
          {
            name: '取消量',
            type: 'bar',
            stack: 'total',
            barWidth: 24,  // 可以直接用数字，单位px
            data: res.data.map(el => el.cancelSaleNum),
            itemStyle: {
              color: '#FF9626',
            }
          },
          {
            name: '预订量',
            type: 'bar',
            stack: 'total',
            barWidth: 24,
            data: res.data.map(el => el.confirmSaleNum),
            itemStyle: {
              color: '#5EB931',
            }
          },
          {
            name: '点击量',
            type: 'bar',
            stack: 'total',
            barWidth: 24,
            data: res.data.map(el => el.clickNum),
            itemStyle: {
              color: '#4C6EE2',
              borderRadius: [6, 6, 0, 0]  // 顶部圆角
            }
          }
        ]
      }

      myChart.setOption(option);
    },
    async cuisineList() {
      // const res = await cuisineGetlist({

      // })
    },
    tcapp() {
      this.$router.push("/urgency")
    },
    // 日历组件事件处理
    handleDateSelected(selectedDate) {
      console.log('选中日期:', selectedDate);

      this.timeApp = selectedDate;
      this.approve();

      // 这里可以根据选中日期加载数据
      // this.loadDataByDate(selectedDate);
    },

    handleWeekChanged(weekRange) {
      console.log('周变化:', weekRange);
      this.timeApp = weekRange.currentSelected;

      this.approve();

      // 这里可以根据周范围加载数据
      // this.loadDataByWeek(weekRange.start, weekRange.end);
    },

    async approve(val) {
      // if (this.$store.state.user.roles.filter(el => el == 'canteen_admin').length > 0) {
      //           params.type = 1;
      //       }
      const res = await getList({
        createTime: this.timeApp || this.getFormattedDate(),
        pageNum: 1,
        pageSize: 4,
        status: 1,
        type: this.$store.state.user.roles.filter(el => el == 'canteen_admin').length > 0 ? 2 : null
      });
      this.urgencyList = res.rows;
    },

    getFormattedDate(date = new Date(), separator = '-') {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return [year, month, day].join(separator);
    },

    getCurrentWeekDates() {
      const today = new Date();
      const dayOfWeek = today.getDay(); // 0是周日，1是周一，...，6是周六

      // 计算周一日期
      const monday = new Date(today);
      monday.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));

      // 计算周日日期
      const sunday = new Date(today);
      sunday.setDate(today.getDate() + (dayOfWeek === 0 ? 0 : 7 - dayOfWeek));

      return {
        monday: this.formatDate(monday),
        sunday: this.formatDate(sunday)
      };
    },

    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    getWeekRange(date) {
      const target = new Date(date); // 复制输入日期，避免修改原对象
      const day = target.getDay() || 7; // 转换为周一为1，周日为7（原生getDay()周日为0）

      // 计算周一（当前日期减去与周一的差值）
      const monday = new Date(target);
      monday.setDate(target.getDate() - (day - 1));
      monday.setHours(0, 0, 0, 0); // 重置时间为当天0点

      // 计算周日（周一加6天）
      const sunday = new Date(monday);
      sunday.setDate(monday.getDate() + 6);
      sunday.setHours(23, 59, 59, 999); // 重置时间为当天23:59:59

      return {
        monday: this.formatDate(monday),
        sunday: this.formatDate(sunday),
        // 格式化显示（例如：2025-09-08 至 2025-09-14）
      };
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，补0
      const day = String(date.getDate()).padStart(2, '0'); // 日期补0
      return `${year}-${month}-${day}`;
    },

    async history(e) {
      console.log(e)
      console.log(this.getWeekRange(e))
      const T = this.getWeekRange(e);
      const res = await historyent({ beginDate: e ? T.monday : this.beginTimeCuisine, endDate: e ? T.sunday : this.overTimeCuisine });
      this.renderHistoryChart(res.data);
    },

    renderHistoryChart(data) {
      const chartDom = document.getElementById('history');
      const myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          // axisPointer: {
          //   lineStyle: {
          //     color: '#4C6EE2'
          //   }
          // },
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          extraCssText: 'box-shadow: none;',
          formatter: function (params) {
            // 获取三种数据的值（兼容可能的数据缺失情况）
            const clickVal = params.find(item => item.seriesName === '本周套餐销量')?.value || 0;
            const bookVal = params.find(item => item.seriesName === '上周销量趋势')?.value || 0;
            const currentComboArr = data.combo[0][params[0].dataIndex].comboDishList;
            console.log(currentComboArr)
            let dishHtml = "";
            if (currentComboArr.length > 0) {
              currentComboArr.forEach((dish, index) => {
                dishHtml += `<div style="color: #999; font-size: 12px; margin-top: 2px; margin-left: 10px;">
                        • ${dish.food_name || '未知菜品'}
                      </div>`;
              });
            } else {
              dishHtml = '<div style="color: #999; font-size: 12px; margin-top: 2px;margin-left:10px;">无本周套餐</div>';
            }

            const currentHistoryComboArr = data.historyCombo[0][params[0].dataIndex].comboDishList;
            let historyDishHtml = "";
            if (currentHistoryComboArr.length > 0) {
              currentHistoryComboArr.forEach((dish, index) => {
                historyDishHtml += `<div style="color: #999; font-size: 12px; margin-top: 2px; margin-left: 10px;">
                        • ${dish.food_name || '未知菜品'}
                      </div>`;
              });
            } else {
              historyDishHtml = '<div style="color: #999; font-size: 12px; margin-top: 2px;margin-left:10px;">无上周套餐</div>';
            }

            console.log(historyDishHtml)



            return `
    <div style="padding: 10px 18px; width:230px; background: #fff; border-radius: 9px; box-shadow: 0px 0px 10px 0px rgba(48, 78, 179, 0.3);">
      <div style="font-weight: bold; color: #333; margin-bottom: 8px; display: flex; align-items: center;">
       
        ${params[0].axisValue} <!-- 使用 axisValue 替代 name 更准确 -->
      </div>
      
     <div >
          <!-- 点击量 -->
          <div style="margin: 6px 0;padding-left:30px;">
             <span style="
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: #4C6EE2;
          position: relative;
        ">
          <span style="
            position: absolute;
            top: 2px;
            left: 2px;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #fff;
          "></span>
        </span>
            <span style="color: #666;">本周套餐销量</span>
            <span style=" font-weight: bold;">${clickVal} </span>
            ${dishHtml}
          </div>
          
          <!-- 预订量 -->
          <div style="margin: 6px 0;padding-left:30px;">
              <span style="
          display: inline-block;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background: #ff9626;
          position: relative;
        ">
          <span style="
            position: absolute;
            top: 2px;
            left: 2px;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #fff;
          "></span>
        </span>
            <span style="color: #666;">上周销量趋势</span>
            <span style=" font-weight: bold;">${bookVal} </span>
            ${historyDishHtml}
          </div>
      </div>
    </div>
  `;
          }
        },
        grid: {
          left: '2%',
          right: '5%',
          bottom: '10%',
          top: "15%",
          containLabel: true
        },
        dataZoom: [{
          type: 'slider',
          xAxisIndex: 0,
          height: 5,
          bottom: 10,
          backgroundColor: '#e0e0e0',
          fillerColor: '#4C6EE2',
          borderColor: 'transparent',
          handleIcon: 'none',
          handleSize: '0%',
          moveHandleSize: 0,
          brushSelect: false,
          showDetail: false,
          borderRadius: 10,
          // 关键配置开始
          minValueSpan: 10,  // 最小显示10个数据项
          startValue: 'dataMin',  // 从第一个数据开始
          endValue: 'dataMax',   // 到最后一个数据结束
          zoomLock: false,      // 允许缩放
          filterMode: 'filter'  // 过滤模式
          // 关键配置结束
        }],
        legend: {
          data: ['本周套餐销量', '上周销量趋势'],
          right: '2%',
        },
        xAxis: [{
          type: 'category',
          data: data.combo[0].map((el,index) => index),
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          },
          axisLabel: {
            padding: [0, 0, 0, 0],
            color: '#323232',
            fontSize: 12,
            interval: 0, // 显示所有标签
            // 关键配置：强制换行
            formatter: function (value, index) {
              // 获取当前套餐对应的菜品列表
              const dishList = data.combo[0][value].comboDishList || [];

              // 提取菜品名称（如果菜品列表存在）
              const dishNames = dishList.map(dish => dish.food_name || '未知菜品');

              // 组合套餐名和菜品（套餐名+每个菜品一行）
              let displayText = data.combo[0][value].combo_name; // 先显示套餐名

              // 如果有菜品，换行后逐个显示
              if (dishNames.length > 0) {
                // 最多显示3个菜品，避免标签过长
                const showDishes = dishNames.slice(0, 3);
                displayText += '\n' + showDishes.join('\n');

                // 如果有更多菜品，显示省略提示
                if (dishNames.length > 3) {
                  displayText += '\n...等' + dishNames.length + '个';
                }
              }

              return displayText;
            },
            lineHeight: 16, // 行高
          },
        }],
        yAxis: [{
          type: 'value',
          name: '单位：份',
          min: 0,
          max: function (value) {
            return (value.max < 5 ? 5 : null); // 向下取整
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          },
          nameTextStyle: {
            padding: [0, 0, 0, "-15"],
            color: '#3D3D3D'
          },
        }],
        series: [
          {
            name: '本周套餐销量',
            type: 'bar',
            data: data.combo[0].map(el => el.combo_count),
            barWidth: 25,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4C6EE2' },
                { offset: 1, color: '#26A3D4' }
              ])
            },
          },
          {
            name: '上周销量趋势',
            type: 'line',
            yAxisIndex: 0,
            data: data.historyCombo[0].map(el => el.combo_count),
            lineStyle: {
              color: '#FF9626'
            },
            itemStyle: {
              color: '#FF9626'
            },
            smooth: true,
          }
        ]
      };

      myChart.setOption(option);
    },

    async board() {
      const { nextMonday, nextSunday } = this.getNextWeekDates();
      const res = await getboard({
        beginDate: this.formatDate(nextMonday),
        endDate: this.formatDate(nextSunday)
      });

      this.boardListNum = res.data.reduce((total, item) => {
        return total + (item.combo_count || 0);
      }, 0);

      // 假设res.data是包含combo_name和combo_count的数组
      const groupedData = res.data.reduce((acc, item) => {
        // 获取当前项的名称和数量（默认0避免undefined）
        const name = item.combo_name;
        const count = Number(item.combo_count) || 0;

        // 检查是否已存在该名称的分组
        const existing = acc.find(group => group.name === name);

        if (existing) {
          // 已存在则累加数量
          existing.count += count;
        } else {
          // 不存在则新增分组
          acc.push({ name, count });
        }

        return acc;
      }, []); // 初始值为空数组

      // 最终结果就是按名称分组并累加后的数组
      this.boardListNumList = groupedData;
      console.log(this.boardListNumList)

      this.renderBoardChart(res.data);
    },

    renderBoardChart(data) {
      const chartDom = document.getElementById('boardl');
      const myChart = echarts.init(chartDom);
      const option = {
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              color: '#4C6EE2'
            }
          },
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          extraCssText: 'box-shadow: none;',
          formatter: function (params) {
            const currentComboArr = data[params[0].dataIndex].comboDishList;
            let dishHtml = "";
            if (currentComboArr.length > 0) {
              currentComboArr.forEach((dish, index) => {
                dishHtml += `<div style="color: #999; font-size: 12px; margin-top: 2px; margin-left: 10px;">
                        • ${dish.food_name || '未知菜品'}
                      </div>`;
              });
            } else {
              dishHtml = '<div style="color: #999; font-size: 12px; margin-top: 2px;margin-left:10px;">无本周套餐</div>';
            }

            console.log(dishHtml)

            
            return `
      <div style="padding: 10px 18px; background: #fff; border-radius: 9px; box-shadow:  0px 0px 10px 0px rgba(48, 78, 179, 0.3);">
        <div style="font-weight: bold; color: #333; margin-bottom: 5px">
         <span style="
              display: inline-block;
              width: 10px;
              height: 10px;
              border-radius: 50%;
              background: #4C6EE2;
              position: relative;
            ">
              <span style="
                position: absolute;
                top: 2px;
                left: 2px;
                width: 6px;
                height: 6px;
                border-radius: 50%;
                background: #fff;
              "></span>
            </span>
          ${params[0].name}
        </div>
        <div style="display: flex; align-items: center;margin-left:15px;color:black;">
          
          <span>${params[0].seriesName}</span>
          <span style=" margin-left: 4px;">${params[0].value} 份</span>
        </div>
           ${dishHtml}
      </div>
    `;
          }
        },
        grid: {
          left: '2%',
          right: '5%',
          bottom: '10%',
          top: "15%",
          containLabel: true
        },
        dataZoom: [{
          type: 'slider',
          xAxisIndex: 0,
          height: 5,
          bottom: 10,
          backgroundColor: '#e0e0e0',
          fillerColor: '#4C6EE2',
          borderColor: 'transparent',
          handleIcon: 'none',
          handleSize: '0%',
          moveHandleSize: 0,
          brushSelect: false,
          showDetail: false,
          borderRadius: 10,
          // 关键配置开始
          minValueSpan: 10,  // 最小显示10个数据项
          startValue: 'dataMin',  // 从第一个数据开始
          endValue: 'dataMax',   // 到最后一个数据结束
          zoomLock: false,      // 允许缩放
          filterMode: 'filter'  // 过滤模式
          // 关键配置结束
        }],
        xAxis: [{
          type: 'category',
          // boundaryGap: false,
          axisLine: {
            lineStyle: {
              color: 'white'
            }
          },
          axisLabel: {
            padding: [0, 0, 0, 0],
            color: '#323232',
            interval: 0, // 显示所有标签
            // 关键配置：强制换行
            formatter: function (value, index) {
            console.log(value)
              // 获取当前套餐对应的菜品列表
              const dishList = data[value].comboDishList || [];

              // 提取菜品名称（如果菜品列表存在）
              const dishNames = dishList.map(dish => dish.food_name || '未知菜品');

              // 组合套餐名和菜品（套餐名+每个菜品一行）
              let displayText = data[value].combo_name; // 先显示套餐名combo_name

              // 如果有菜品，换行后逐个显示
              if (dishNames.length > 0) {
                // 最多显示3个菜品，避免标签过长
                const showDishes = dishNames.slice(0, 3);
                displayText += '\n' + showDishes.join('\n');

                console.log(dishNames)
                // 如果有更多菜品，显示省略提示
                if (dishNames.length > 3) {
                  displayText += '\n...等' + dishNames.length + '个';
                }
              }

              return displayText;
            },
            lineHeight: 16, // 行高
            fontSize: 12    // 缩小字体
          },
          data: data.map((el,index) => index)
        }],
        yAxis: [{
          type: 'value',
          name: '单位：份',
          splitNumber: 5,
          nameTextStyle: {
            padding: [0, 0, 0, "-15"],
            color: '#3D3D3D'
          },
          min: 0,
          max: function (value) {
            return (value.max < 5 ? 5 : null); // 向下取整
          },
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              type: 'dashed',
              color: '#3D3D3D'
            }
          },
          axisLabel: {
            // margin: 20,
            textStyle: {
              fontSize: 14,
              color: '#3D3D3D'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#ddd'
            }
          },
        }],
        series: [{
          name: '预定量：',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          showSymbol: false,
          emphasis: {
            scale: 1.2,
            itemStyle: {
              color: 'transparent',
              borderColor: '#4C6EE2',
              borderWidth: 2
            },
            focus: 'series'
          },
          lineStyle: {
            normal: {
              width: 2,
              color: '#4C6EE2'
            }
          },
          areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(76, 110, 226, 0.3)'
              }, {
                offset: 0.8,
                color: 'rgba(0, 136, 212, 0)'
              }], false),
              shadowColor: 'rgba(0, 0, 0, 0.1)',
              shadowBlur: 10
            }
          },
          itemStyle: {
            normal: {
              color: 'rgb(0,136,212)',
              borderColor: 'rgba(0,136,212,0.2)',
              borderWidth: 12
            }
          },
          data: data.map(el => el.combo_count)
        }]
      };

      myChart.setOption(option);
    },

    getNextWeekDates() {
      const today = new Date();
      const currentDay = today.getDay();
      const daysToNextMonday = currentDay === 1 ? 7 : (1 - currentDay + 7) % 7;
      const nextMonday = new Date(today);
      nextMonday.setDate(today.getDate() + daysToNextMonday);

      const nextSunday = new Date(nextMonday);
      nextSunday.setDate(nextMonday.getDate() + 6);

      return {
        nextMonday: nextMonday,
        nextSunday: nextSunday
      };
    },

    getIpAddress() {
      let year = new Date().getFullYear();
      fetch(`https://${year}.ip138.com/`)
        .then(x => x.text())
        .then(h => {
          let domParser = new DOMParser();
          let doc = domParser.parseFromString(h, "text/html");
          let text = doc?.querySelector('p')?.innerText?.trim();

          try {
            let ip = text.substring(text.indexOf("[") + 1, text.indexOf("]")).trim();
            this.ipAddress.ip = ip;
            let other = text.substring(text.indexOf("来自：") + 3).trim();
            let arr = other.split(" ");
            this.ipAddress.location = arr[0];
            this.ipAddress.type = arr[1];
          } catch (e) {
            console.error(e);
          }
        });
    },

    handleApprove(row) {
      this.$confirm('确定要同意该审批吗?', '提示', {
        type: 'warning'
      }).then(() => {
        if (row.type == 1) {
          return submitApproval({
            id: row.id,
            type: row.type,
            code: row.code,
            status: '2' // 0表示同意
          })
        } else {
          return changerovall({
            changeOrderId: row.changeOrderId,
            code: row.code,
            id: row.id,
            status: '2' // 0表示同意
          })
        }
      }).then(() => {
        this.$message.success('审批已同意');
        this.approve();
      });
    },

    handleReject(row) {
      this.$confirm('确定要拒绝该审批吗?', '提示', {
        type: 'warning'
      }).then(() => {
        if (row.type == 1) {
          return submitApproval({
            id: row.id,
            type: row.type,
            code: row.code,
            status: '3' // 1表示拒绝
          })
        } else {
          return changerovall({
            changeOrderId: row.changeOrderId,
            code: row.code,
            id: row.id,
            status: '3' // 1表示拒绝
          })
        }
      }).then(() => {
        this.$message.success('审批已拒绝');
        this.approve();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.card-wrap {
  position: relative;
  width: 33%;
  height: 100%;
}

.card-inner {
  background: #fff;
  border-radius: 5px;
  height: 100%;
  display: flex;
  padding-left: 40px;
  box-sizing: border-box;
}

.icon {
  width: 83px;
  height: 83px;
  margin-top: 34px;
}

.info {
  margin-top: 34px;
  margin-left: 23px;
}

.label {
  font-size: 14px;
  color: #848484;
}

.count {
  font-size: 24px;
  color: #000;
  margin: 8px 0;
}

.sub {
  font-size: 14px;
  color: red;
}

.box {
  width: 400px;

  .top {
    text-align: center;
  }

  .left {
    float: left;
    width: 60px;
  }

  .right {
    float: right;
    width: 60px;
  }

  .bottom {
    clear: both;
    text-align: center;
  }

  .item {
    margin: 4px;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}

/* 弹框 */
.pop-list {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 999;
  width: 460px;
  left: -30px;
  max-height: 260px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, .15);
  padding: 8px 0;
  margin-top: 4px;
}

.pop-item {
  // padding: 6px 0px;
  padding-bottom: 0px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  white-space: nowrap;
}

.pop-item:last-child {
  border-bottom: none;
}

.pop-item:hover {
  background: #f7f7f7;
}

.empty {
  padding: 10px;
  text-align: center;
  color: #999;
}

::v-deep .el-table th.el-table__cell {
  background-color: rgb(241, 244, 253) !important;
  color: #323232;
  /* 字体颜色可选，改白色更清楚 */
}

/* 必须使用 ::v-deep 或 /deep/ 才能覆盖 Element-UI 的内部样式 */
::v-deep .el-table .even-row {
  background-color: rgb(252, 252, 255) !important;
}

/* 可选：去掉 hover 高亮（如果不需要） */
::v-deep .el-table tbody tr:hover>td {
  background-color: transparent !important;
}

.activeche {
  background: url("../assets/images/xuanz.png")no-repeat;
  background-size: 100% 100%;
  /* 或 cover / contain */
}

.activeches {
  background: url("../assets/images/weixuaz.png") no-repeat;
  background-size: 100% 100%;
  /* 或 cover / contain */
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: block;
}

/* 调整输入框内部样式 */
::v-deep .el-date-editor.el-input {
  width: 117px;
  height: 26px;
}

::v-deep .el-date-editor .el-input__inner {
  height: 26px;
  line-height: 26px;
  padding: 0 10px;
  font-size: 12px !important;
}

/* 隐藏图标 */
::v-deep .el-date-editor .el-input__prefix,
.el-date-editor .el-input__suffix {
  display: none;
}

/* 调整下拉面板样式 */
::v-deep .small-date-picker {
  font-size: 12px;
}

::v-deep .small-date-picker .el-picker-panel__content {
  margin: 5px;
}

.app-container {
  padding: 5px;
  box-sizing: border-box;
  background-color: rgb(243, 251, 248);
}

.row-block {
  height: 545px;
}

.row-blocks {
  height: 43%;
  margin-bottom: 5px;
}

.left-combo {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding-right: 5px;
}

.left-top,
.left-middle {
  padding-bottom: 5px;
}

.section-card {
  height: 100%;
  margin: 0;
  border-radius: 8px;
}

.section-content {
  padding: 12px;
  height: 100%;
  overflow: auto;
  background: white;
  border-radius: 3px;
}

/* 背景色调整 */
.left-top .section-content {
  background: #f0f9eb;
}

.left-middle .section-content {
  background: #fdf6ec;
}

.left-bottom .section-content {
  background: #fef0f0;
}

.right-top .section-content {
  background: #ecf5ff;
}

.right-bottom .section-content {
  background: #f9f0ff;
}
</style>